package com.cqrt.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqrt.config.ConfigurableFieldsConfig;
import com.cqrt.constant.RTErrorCodeEnum;
import com.cqrt.dto.TaskMessageDTO;
import com.cqrt.dto.TemplateDTO;
import com.cqrt.entity.PlanTemplate;
import com.cqrt.mapper.PlanTemplateMappper;
import com.cqrt.mapper.RTProjectMapper;
import com.cqrt.mapper.RTTaskMapper;
import com.cqrt.service.RTProjectTemplateService;
import com.cqrt.vo.ProjectManagerVO;
import com.cqrt.vo.RTJobVO;
import com.hustcad.plm.pdm.core.base.EntityBase;
import com.hustcad.plm.pdm.core.handle.exception.SystemErrorCodeEnum;
import com.hustcad.plm.pdm.core.response.TyppmResponseResult;
import com.hustcad.plm.rpm.model.dto.active.ImportActiveDTO;
import com.hustcad.plm.rpm.model.dto.active.ImportChildActiveDTO;
import com.hustcad.plm.rpm.model.dto.active.PlusTaskDTO;
import com.hustcad.plm.rpm.model.dto.calendar.TyppmCalendarDTO;
import com.hustcad.plm.rpm.model.dto.library.LibNodeTreeDTO;
import com.hustcad.plm.rpm.model.dto.message.ObjectMsgTempLinkDTO;
import com.hustcad.plm.rpm.model.entity.plan.TyppmPlanActive;
import com.hustcad.plm.rpm.model.vo.message.ObjectMsgTempLinkVO;
import com.hustcad.plm.rpm.model.vo.project.ProjectTemplateVO;
import com.hustcad.plm.rpm.service.importdata.TyppmImportDataService;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.ppm.model.constant.ApiPathConstant;
import com.ty.ppm.model.entity.job.Job;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import java.util.function.Function;
import java.util.stream.Collectors;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;


@RestController
@Api(tags = "项目模板")
@RequestMapping(ApiPathConstant.PARENT_VERSION_ONE_PATH + "ppm")
@Slf4j
public class RTProjectTemplateController {

    @Resource
    private RTProjectTemplateService projectTemplateService;
    @Resource
    private ConfigurableFieldsConfig configurableFieldsConfig;
    @Resource
    private PlanTemplateMappper planTemplateMappper;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;

    @Resource
    private TyppmImportDataService typpmImportDataService;
    @Resource
    private RTTaskMapper rtTaskMapper;
    @Resource
    private RTProjectMapper rtProjectMapper;

    @GetMapping("/getEnum")
    @ApiOperation(value = "获取计划模板枚举值", produces = "application/json; charset=utf-8")
    public TyppmResponseResult<Map<String, Map<String, String>>> getProjectAttr() {
        Map<String, Map<String, String>> AttrMap= projectTemplateService.getAttr(configurableFieldsConfig.getFields());
        Map<String, String> developmentLevel = AttrMap.get("developmentLevel");
        LinkedHashMap<String, String> newMap = developmentLevel
                .entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
                                          LinkedHashMap::new));
        AttrMap.put("developmentLevel",newMap);
        return TyppmResponseResult.success(AttrMap);
    }

    @GetMapping("/getConditionByTemplate")
    @ApiOperation(value = "根据条件筛选任务模板", produces = "application/json; charset=utf-8")
    public LibNodeTreeDTO getConditionByTemplate(String key) {
        return projectTemplateService.getChildrenByParent(key);
    }

    @PutMapping("/updateTemplateStatus")
    @ApiOperation(value = "更新项目模板状态", produces = "application/json; charset=utf-8")
    public ResponseResult<T> updateTemplateStatus(String projectId, String status) {
        projectTemplateService.updateTemplateStatus(projectId, status);
        return ResponseResult.success();
    }

    @PostMapping({"/batchImportChildPlanActiveByPlanTemplate"})
    @ApiOperation(
            value = "批量通过计划模板导入活动",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<List<PlusTaskDTO>> batchImportChildPlanActiveByPlanTemplate(@RequestBody List<ImportChildActiveDTO> importActiveDTOs) {
        List<PlusTaskDTO> plusTaskDTOList = projectTemplateService.batchImportChildPlanActiveByPlanTemplatePlus(importActiveDTOs);
        return TyppmResponseResult.success(JSON.parseArray(JSON.toJSONString(plusTaskDTOList)));
    }

//导入一级任务（上一个是子任务）
    @PostMapping({"/batchImportPlanActiveByPlanTemplate"})
    @ApiOperation(
            value = "批量通过计划模板导入活动",
            produces = "application/json; charset=utf-8"
    )

    public TyppmResponseResult<List<PlusTaskDTO>> batchImportPlanActiveByPlanTemplate(@RequestBody List<ImportChildActiveDTO> importActiveDTOs) {

        List<PlusTaskDTO> plusTaskDTOList = projectTemplateService.batchImportChildPlanActiveByPlanTemplatePlus(importActiveDTOs);
        for (PlusTaskDTO plusTaskDTO : plusTaskDTOList){
            plusTaskDTO.setParentOID(plusTaskDTO.getRootOID());
//            if (StrUtil.isBlank(plusTaskDTO.getSourceActiveOid())){
//                List<TyppmPlanActive> typpmPlanActives = rtProjectMapper.selectPlanActiveByProjectId(new BigInteger(plusTaskDTO.getRootOID()));
//                String oid = typpmPlanActives.get(0).getOid();
//                plusTaskDTO.setSourceActiveOid(oid);
//            }
        }//List<PlusTaskDTO> plusTaskDTOList = projectTemplateService.batchImportPlansActiveByPlanTemplatePlus(importActiveDTOs);
        return TyppmResponseResult.success(JSON.parseArray(JSON.toJSONString(plusTaskDTOList)));
    }

//    @PostMapping({"/batchImportPlanActiveByPlanTemplate"})
//    @ApiOperation(
//            value = "批量通过计划模板导入活动",
//            produces = "application/json; charset=utf-8"
//    )
//    public TyppmResponseResult<List<PlusTaskDTO>> batchImportPlanActiveByPlanTemplate(@RequestBody ImportActiveDTO importActiveDTO) {
//        List<PlusTaskDTO> plusTaskDTOS = projectTemplateService.batchImportPlanActiveByPlanTemplatePlus(importActiveDTO);
//        // List<PlusTaskDTO> plusTaskDTOList = projectTemplateService.batchImportPlansActiveByPlanTemplatePlus(importActiveDTOs);
//        return TyppmResponseResult.success(JSON.parseArray(JSON.toJSONString(plusTaskDTOS)));
//    }

    @PostMapping({"/importPlanActiveByExcel"})
    @ApiOperation(
            value = "通过Excel导入一级任务",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<JSONArray> importSubPlanActiveByExcel(String planActiveOid, MultipartFile file) {
        BigInteger parent = rtTaskMapper.selectParentByJobId(planActiveOid);
        if (parent != null){
            planActiveOid = parent.toString();
        }else {
            throw RTErrorCodeEnum.TASK_FIRST_ERROR.getException("任务不存在，无法导入");
        }
        return TyppmResponseResult.success(this.typpmImportDataService.importSubPlanActiveByExcel(planActiveOid, file));
    }


    @PostMapping({"/batchUpdateCalendarExceptionDayList"})
    @ApiOperation(
            value = "批量导入项目日历例外日期",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult batchUpdateCalendarExceptionDayList(
            @RequestBody  List<String> projectList,
            String projectOid) {
        projectTemplateService.batchUpdateCalendarExceptionDayList(projectList,projectOid);
        return TyppmResponseResult.success();
    }

    @PostMapping({"/batchUpdateCalendarDTOList"})
    @ApiOperation(
            value = "批量更新项目日历",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<List<TyppmCalendarDTO>> updateCalendarDTOList(
            @RequestBody List<String> projectList,
            String projectOid) {
        List<TyppmCalendarDTO> calendarDTOS = projectTemplateService.batchUpdateCalendarDTOList(projectList,
                                                                                                projectOid);
        return TyppmResponseResult.success(calendarDTOS);
    }

    @PostMapping({"/getChildrenByParentPlus"})
    @ApiOperation(
            value = "创建项目引用模板库",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<List<EntityBase>> getChildrenByParentPlus(@RequestBody TemplateDTO templateDTO) {
        List<EntityBase> list = this.projectTemplateService.getChildrenByParentPlus(templateDTO);
        return TyppmResponseResult.success(list);
    }

    @PostMapping({"/batchCreateObjectMessageLink"})
    @ApiOperation(
            value = "批量新增消息模板关系",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<ObjectMsgTempLinkVO> batchCreateObjectMessageLink(
             @RequestBody List<ObjectMsgTempLinkDTO> requestParams, String planOID) {
        if (ObjectUtils.isEmpty(requestParams)) {
            throw SystemErrorCodeEnum.ARGUMENT_NONE.message(new Object[]{"params"});
        } else {
            projectTemplateService.batchCreateObjectMessageLink(requestParams, planOID);
            return TyppmResponseResult.success();
        }
    }

    @PostMapping({"/batchUpdateMessageTemplateDefine"})
    @ApiOperation(
            value = "批量修改消息模板关系",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<ObjectMsgTempLinkVO> batchUpdateMessageTemplateDefine(
            @RequestBody List<ObjectMsgTempLinkDTO> requestParams, String planOID) {
        if (ObjectUtils.isEmpty(requestParams)) {
            throw SystemErrorCodeEnum.ARGUMENT_NONE.message(new Object[]{"params"});
        } else {
            projectTemplateService.batchUpdateMessageTemplateDefine(requestParams, planOID);
            return TyppmResponseResult.success();
        }
    }

    @PostMapping({"/batchDeleteObjectMessageLinkList"})
    @ApiOperation(
            value = "批量删除任务消息",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<Integer> batchDeleteObjectMessageLinkList(
            @RequestBody List<String> requestParams, String planOID) {
        if (ObjectUtils.isEmpty(requestParams)) {
            throw SystemErrorCodeEnum.ARGUMENT_NONE.message(new Object[]{"params"});
        } else {
            projectTemplateService.batchDeleteObjectMessageLinkList(requestParams, planOID);
            return TyppmResponseResult.success();
        }
    }

    @PostMapping({"/batchOperationObjectMessageLinkList"})
    @ApiOperation(
            value = "批量维护任务消息",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<Integer> batchOperationObjectMessageLinkList(
            @RequestBody TaskMessageDTO taskMessageDTO) {
        if (ObjectUtils.isEmpty(taskMessageDTO.getRequestParam())) {
            throw SystemErrorCodeEnum.ARGUMENT_NONE.message(new Object[]{"params"});
        } else {
            projectTemplateService.batchOperationObjectMessageLinkList(taskMessageDTO);
            return TyppmResponseResult.success();
        }
    }

    @PostMapping({"/getTemplateChildrenByParentPlus"})
    @ApiOperation(
            value = "创建模板引用模板库",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<List<EntityBase>> getTemplateChildrenByParentPlus(@RequestBody TemplateDTO templateDTO) {
        List<EntityBase> list = this.projectTemplateService.getTemplateChildrenByParentPlus(templateDTO);
        return TyppmResponseResult.success(list);
    }


    @PostMapping({"/getPlanChildrenByParentPlus"})
    @ApiOperation(
            value = "导入项目计划引用模板库",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<List<EntityBase>> getPlanChildrenByParentPlus(@RequestBody TemplateDTO templateDTO) {
        List<EntityBase> list = this.projectTemplateService.getPlanChildrenByParentPlus(templateDTO);
        return TyppmResponseResult.success(list);
    }


    @PostMapping({"/getAllChildrenByParentPlus"})
    @ApiOperation(
            value = "创建项目引用模板库(全量)",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<LibNodeTreeDTO> getAllChildrenByParentPlus(@RequestBody TemplateDTO templateDTO) {
        LibNodeTreeDTO libNodeTreeDTO = this.projectTemplateService.getAllChildrenByParentPlus(templateDTO);
        return TyppmResponseResult.success(libNodeTreeDTO);
    }


//    @PostMapping({"/selectTemplateValueByOId"})
//    @ApiOperation(
//            value = "根据模板OID查询模板详情",
//            produces = "application/json; charset=utf-8"
//    )
//    public TyppmResponseResult<ProjectTemplateVO> selectTemplateValueByOId(@RequestBody String templateOid) {
//        ProjectTemplateVO projectTemplateVO = projectTemplateService.selectTemplateValueByOId(templateOid);
//        return TyppmResponseResult.success(projectTemplateVO);
//    }



    @PostMapping({"/batchImportPlanActiveByPlanTemplatePlus"})
    @ApiOperation(
            value = "通过计划模板批量导入活动",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<JSONArray> batchImportPlanActiveByPlanTemplatePlus(@RequestBody ImportActiveDTO importActiveDTO) {
        List<PlusTaskDTO> plusTaskDTOList = this.projectTemplateService.batchImportPlanActiveByPlanTemplatePlus(importActiveDTO);
        if (CollUtil.isNotEmpty(plusTaskDTOList)) {
            String temp = planTemplateMappper.selectPlanExist(importActiveDTO.getCurPlanOID());
            if (StrUtil.isBlank(temp)){
                String oid = plusTaskDTOList.get(0).getSourceActiveOid();
                String rootId = planTemplateMappper.selectRootIdByoid(oid);
                PlanTemplate planTemplate = new PlanTemplate();
                planTemplate.setOid(snowflakeIdComponent.getInstance().nextId().toString());
                planTemplate.setAoid(importActiveDTO.getCurPlanOID());
                planTemplate.setBoid(rootId);
                planTemplate.setModifystamp(LocalDateTime.now());
                planTemplate.setCreatestamp(LocalDateTime.now());
                planTemplate.setUpdatestamp(LocalDateTime.now());
                planTemplate.setUpdatecount(new BigInteger("0"));
                planTemplateMappper.insertPlanTemplate(planTemplate);
            }else {
                String oid = plusTaskDTOList.get(0).getSourceActiveOid();
                String rootId = planTemplateMappper.selectRootIdByoid(oid);
                planTemplateMappper.updatePlanTemplate(importActiveDTO.getCurPlanOID(),rootId);
            }

        }
        return TyppmResponseResult.success(JSON.parseArray(JSON.toJSONString(plusTaskDTOList)));
    }

    @GetMapping({"/querySimilarTemplate"})
    @ApiOperation(
            value = "创建项目引用模板库(全量)",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<JSONObject> querySimilarTemplate(String templateDTO) {
        JSONObject data = this.projectTemplateService.querySimilarTemplate(templateDTO);
        return TyppmResponseResult.success(data);
    }

    @PostMapping({"/batchReplaceProjectManger"})
    @ApiOperation(
            value = "批量替换项目管理员",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult batchReplaceProjectManger(@RequestBody JSONObject params) {
        this.projectTemplateService.batchReplaceProjectManger(params);
        return TyppmResponseResult.success();
    }

    @PostMapping({"/selectProjectByManger"})
    @ApiOperation(
            value = "根据项目管理员查询项目",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<List<ProjectManagerVO>> selectProjectByManger(@RequestBody JSONObject params) {
        List<ProjectManagerVO> data = this.projectTemplateService.selectProjectByManger(params);
        return TyppmResponseResult.success(data);
    }

    @PostMapping({"/selectProjectByMember"})
    @ApiOperation(
            value = "根据项目成员查询项目",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<List<ProjectManagerVO>> selectProjectByMember(@RequestBody JSONObject jsonObject) {
        String member = jsonObject.getString("member");
        String projectName = jsonObject.getString("projectName");
        String projectNumber = jsonObject.getString("projectNumber");
        String thisYear = jsonObject.getString("thisYear");
        if (StrUtil.isBlank(member)){
            return TyppmResponseResult.fail(400,"参数member不能为空！");
        }
        List<ProjectManagerVO> data = this.projectTemplateService.selectProjectByMember(member,projectName,projectNumber,thisYear);
        List<ProjectManagerVO> result = data.stream().collect(
                        Collectors.toMap(ProjectManagerVO::getProjectName, Function.identity(), (e, r) -> e)).values().stream()
                .collect(Collectors.toList());

        return TyppmResponseResult.success(result);
    }

    @PostMapping({"/selectJobByMember"})
    @ApiOperation(
            value = "根据项目成员查询任务",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult<List<Job>> selectJobByMember(@RequestBody JSONObject jsonObject) {
        String member = jsonObject.getString("member");
        String projectName = jsonObject.getString("projectName");
        String projectNumber = jsonObject.getString("projectNumber");
        String prjId = jsonObject.getString("projectId");
        String tags = jsonObject.getString("tags");
        String jobName="";
        if (StrUtil.isNotBlank(jsonObject.getString("displayFullName"))) {
             jobName = jsonObject.getString("displayFullName");
        }
        String thisYear = jsonObject.getString("thisYear");
        if (StrUtil.isBlank(member)){
            return TyppmResponseResult.fail(400,"参数member不能为空！");
        }
        List<Job> data = rtTaskMapper.selectJobByUserId(member,prjId,jobName);
        List<Job> result = data.stream().collect(
                        Collectors.toMap(Job::getName, Function.identity(), (e, r) -> e)).values().stream()
                .collect(Collectors.toList());
        for (int i=result.size()-1;i>=0;i--){
            BigInteger oid = result.get(i).getOid();
            BigInteger planActiveOid=rtProjectMapper.selectPlanActiveByJobId(oid);
            if (planActiveOid!=null){
                List<String> workName=rtProjectMapper.selectWorkName(planActiveOid);
                boolean flag=false;
                for (String name:workName){
                    if(tags.equals(name)) {
                        flag=true;

                    }
                }
                if (!flag){
                    result.remove(i);
                }

            }
        }

        List<RTJobVO> newResult=new ArrayList<>();
        for (Job job:result){
            RTJobVO rtJobVO=new RTJobVO();
            BeanUtils.copyProperties(job,rtJobVO);
            rtJobVO.setOid(job.getOid().toString());
            BigInteger pjoid = rtProjectMapper.selectProjectById(job.getOid());
            if (pjoid!=null) {
                rtJobVO.setProjectID(pjoid.toString());
            }
            rtJobVO.setActivityID(job.getActivityID().toString());
            rtJobVO.setPlanoid(job.getPlanoid().toString());
            rtJobVO.setExecutorOID(job.getExecutorOID().toString());
            newResult.add(rtJobVO);
        }

        return TyppmResponseResult.success(newResult);
    }

    @PostMapping({"/batchDeleteProjectManger"})
    @ApiOperation(
            value = "根据项目管理员查询项目",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult batchDeleteProjectManger(@RequestBody JSONObject params) {
        this.projectTemplateService.batchDeleteProjectManger(params);
        return TyppmResponseResult.success();
    }

    @PostMapping({"/batchReplaceJobExecutor"})
    @ApiOperation(
            value = "批量替换项目任务执行者",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult batchReplaceJobExecutor(@RequestBody JSONObject params) {
        try {
            this.projectTemplateService.batchReplaceJobExecutor(params);
        } catch (Exception e) {
            e.printStackTrace();
            throw RTErrorCodeEnum.UPDATA_PROJECT_MANAGER_ERROR.getException(e.getMessage());
        }
        return TyppmResponseResult.success();
    }


    @PostMapping({"/batchReplaceJobExecutorEX"})
    @ApiOperation(
            value = "批量替换项目任务执行者",
            produces = "application/json; charset=utf-8"
    )
    public TyppmResponseResult batchReplaceJobExecutorEX(@RequestBody JSONObject params) {
        try {
            this.projectTemplateService.batchReplaceJobExecutorEX(params);
        } catch (Exception e) {
            e.printStackTrace();
            throw RTErrorCodeEnum.UPDATA_PROJECT_MANAGER_ERROR.getException(e.getMessage());
        }
        return TyppmResponseResult.success();
    }

}
